package cn.xxm.scene.validate.processor;




import cn.xxm.scene.validate.annotation.VDate;
import cn.xxm.scene.validate.exception.ValidateException;
import cn.xxm.scene.validate.response.ResponseInfo;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


@SuppressWarnings("rawtypes")
public class DateProcessor extends ValidateProcessor {
	private long minTime = -1L;
	private long maxTime = -1L;
	private SimpleDateFormat dateFormat;
	
	@SuppressWarnings({ "unchecked"})
	public DateProcessor(VDate vDate){
		Class<Enum> enumClass = (Class<Enum>)vDate.enumClass();
		Enum enumInstance = Enum.valueOf(enumClass, vDate.enumName());
		if(! (enumInstance instanceof ResponseInfo)) {//枚举类型没实现ResponseInfo则抛异常
			throw new ValidateException("枚举类型<"+enumClass+">未实现接口<"+ResponseInfo.class+">")  ;
		}
		super.setResponseInfo(enumInstance);
		dateFormat = new SimpleDateFormat(vDate.pattern());
		String pattern = vDate.pattern();
		String min = vDate.min();
		String max = vDate.max();
		try {
			dateFormat = new SimpleDateFormat(pattern);
			minTime = dateFormat.parse(min).getTime();
			maxTime = dateFormat.parse(max).getTime();
		} catch (Exception e) {
			logger.error("init DateProcessor error,pattern={},min={},max={}",pattern,min,max);
		}
	}

	@Override
	public boolean validate(Object value) {
		long time;
		if(value instanceof Date){
			Date date = (Date) value;
			time = date.getTime();
		}else if(value instanceof Calendar){
			Calendar calendar = (Calendar) value;
			time = calendar.getTimeInMillis();
		}else{
			try {
				Date date = dateFormat.parse(value.toString());
				time = date.getTime();
			} catch (Exception e) {
				return false;
			}
		}
		if(minTime > -1L && time < minTime){
			return false;
		}
		if(maxTime > -1L && time > maxTime){
			return false;
		}
		return true;
	}
}
